
//
//  OptionCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/3/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit





protocol OptionCellDelegate {
    func didSelectCell (at indexPath: IndexPath, optionIndex: Int?)
}

final class OptionCell: UITableViewCell {
    
    // MARK: - Outlets
    
    private lazy var mainView: OptionItem = {
        let view = OptionItem()
        return view
    }()
    
    private lazy var itemsStack: UIStackView = {
        let stack = UIStackView()
        stack.spacing = 8.0
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .equalSpacing
        return stack
    }()
    
    
    // MARK: - Props
    
    var optionModel: OptionViewModel! {
        didSet {
            self.updateCell(oldValue: oldValue)
            mainView.updateExpand(isExpanded: optionModel.isExpanded!)
            mainView.initialize(isSingle: optionModel.option.isSingle ?? false,
                                title: optionModel.title, isMain: true, textColor: .darkBlueColor)
        }
    }
    var delegate: OptionCellDelegate!
    var indexPath: IndexPath!
    
    private var isCarCreate: Bool = false
    
    // MARK: - Action
   
    @objc func didSelect (option: OptionTap) {
        delegate.didSelectCell(at: option.indexPath, optionIndex: option.optionIndex)
    }
    
    // MARK: - Init
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        let size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
        return CGSize(width: size.width, height: max(size.height, 72.0))
    }
    
    
    private func addView () {
        self.contentView.addSubview(mainView)
        mainView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalToSuperview()
        }
    }
    private func addStack () {
        self.contentView.addSubview(itemsStack)
        itemsStack.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalTo(mainView.snp.bottom).offset(8)
            make.bottom.equalToSuperview().inset(8)
        }
    }
}


extension OptionCell {
    
    func addTap (isCarCreate: Bool = false) {
        
        let tap = OptionTap(target: self, action: #selector(didSelect(option:)))
        tap.indexPath = self.indexPath
        mainView.addGestureRecognizer(tap)
        
        self.mainView.isCarCreate = isCarCreate
        self.isCarCreate = isCarCreate
    }
    
    private func updateCell (oldValue: OptionViewModel?) {
        
        mainView.updateExpand(isExpanded: optionModel.isExpanded!)
        mainView.updateSelection(isSelected: optionModel.option.isSelected ?? false)
        
        if (!(optionModel.option.isSingle ?? false)) {
            if (optionModel.isExpanded ?? false) {
                _ = itemsStack.arrangedSubviews.map {
                    $0.removeFromSuperview()
                }
                itemsStack.removeFromSuperview()
                self.addItems(items: optionModel.option.items ?? [])
            } else {
                _ = itemsStack.arrangedSubviews.map {
                    $0.removeFromSuperview()
                }
                itemsStack.removeFromSuperview()
            }
        }
    }
    
    private func addItems (items: [OptionViewModel.Option]) {
        self.addStack()
        for (i, item) in items.enumerated() {
            let view = createItemView(item: item)
            
            let tap = OptionTap(target: self, action: #selector(didSelect(option:)))
            tap.indexPath = self.indexPath
            tap.optionIndex = i
            view.updateSelection(isSelected: item.isSelected ?? false)
            
            view.addGestureRecognizer(tap)
            itemsStack.addArrangedSubview(view)
        }
    }
    
    private func createItemView (item: OptionViewModel.Option) -> OptionItem {
        let itemView = OptionItem()
        itemView.isCarCreate = isCarCreate
        itemView.initialize(isSelected: item.isSelected, isSingle: true, title: item.name, isMain: false, textColor: .darkBlueColor)
        return itemView
    }
}
